var errdetail = $.extend(Douban.errdetail, {
    20: '抱歉，图片短边尺寸不能小于400像素',
    21: '信息不全，请刷新页面重试。'
});

var allFilesUploaded = 0,
    allErrorFiles = 0,
    uploadStarted = false,
    totalNum = 0,
    totalSize = 0,
    idsFiled,
    ids = '';

function updateTotal (num, size) {
    $('#upload-status .num b').text(num);
    $('#upload-status .total-size b').text(size/1024 < 1024 ? (size/1024).toFixed(1) + ' KB' : (size/1024/1024).toFixed(2) + ' MB');
}

function fileQueued (file) {
    var thisobj = this,
        progress = new FileProgress(file, thisobj.customSettings.progressTarget);

    totalNum += 1;
    totalSize += file.size;

    progress.toggleCancel(true, thisobj);

    if(!uploadStarted) {
        $('.upload-tips').addClass('hidden');

        // hack: 避开 flash 的安全策略隐藏按钮
        $('#upload-btn').css({ opacity: 0, height: 0 });

        $('.opt-btns, .upload-list, #upload-status').removeClass('hidden');
        $('#upload-status .num b').text(file.index + 1);
        $('.progressBarInProgress').addClass('hidden');

        if ($('.progressWrapper').length === 20) {
            $('.continue-wrapper').addClass('hidden');
        }

        updateTotal(totalNum, totalSize);
        //uploadStarted = true;
    }
}

function swfuploadLoadFailed () {
    $('#noflash').show();
    $('#old-portal').show();
}

function preload () { }

function debug_message (obj, error, file, message) {
    obj.debug('Error Code: ' + error + ', File name: ' + file.name + ', File size: ' + file.size + ', Message: ' + message);
}

function decrease_upload_count (obj) {
    allFilesUploaded--;
    var stats = obj.getStats();
    stats.successful_uploads--;
    obj.setStats(stats);
}

function fileQueueError (file, errorCode, message) {
    //console.log('> file queue error');
    var thisobj = this;
    if (errorCode === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) {
        alert('你选择了太多的文件,\n' + (message === 0 ? '达到了上传的上限' : '你最多可以选择 ' + message + ' 个文件。'));
        return;
    }

    var progress = new FileProgress(file, this.customSettings.progressTarget);
    //alert('progress set error');
    progress.setError();
    //alert('progress toggle cancel');
    progress.toggleCancel(true, thisobj);

    switch (errorCode) {
        case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
            progress.setStatus(errdetail[2]); // 文件过大
            //debug_message(this, 'File too big', file, message);
            break;

        case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
            progress.setStatus('不能上传大小为0的文件。');
            //debug_message(this, 'Zero byte file', file, message);
            break;

        case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
            progress.setStatus(errdetail[12]);
            debug_message(this, 'Invalid file type', file, message);
            break;

        default:
            if (file !== null) {
                progress.setStatus('错误');
            }
            debug_message(this, errorCode, file, message);
            break;
        }
        //console.log('< file queue error done');
}

function fileDialogComplete(numFilesSelected, numFilesQueued) {
    //console.log('> file dialog complete');
    var thisobj = this;

    if (numFilesSelected > 0) {
        document.getElementById(this.customSettings.cancelButtonId).disabled = false;
    }

    //console.log('< file dialog complete done');
}

function uploadStart (file) {
    //console.log('> upload start');
    $('.continue-wrapper').addClass('hidden');
    $('#upload-start').val('上传中...').attr('disabled', 'disabled');
    $('.progressBarInProgress').removeClass('hidden');

    var progress = new FileProgress(file, this.customSettings.progressTarget);
    //progress.setStatus('上传中...');
    progress.toggleCancel(true, this);
    return true;
}

function uploadProgress (file, bytesLoaded, bytesTotal) {
    var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
    var progress = new FileProgress(file, this.customSettings.progressTarget);
    progress.setProgress(percent);
    //progress.setStatus('上传中，' + percent + '% 已完成');
}

function uploadSuccess (file, serverData) {
    var progress = new FileProgress(file, this.customSettings.progressTarget),
        res = $.parseJSON(serverData),
        thisobj = this;

    if (res.error) {

        progress.setError();
        progress.setStatus(errdetail[res.error]);

        // update error file number
        allErrorFiles++;
        console.log('uploadSuccess'+allErrorFiles);

        progress.toggleCancel(true, thisobj, function () {
            progress.disappear();
            decrease_upload_count(thisobj);
        });

        return false;

    } else {
        progress.setComplete();
        progress.setStatus('成功');
        progress.removeDelIcon(res.id);
        $('.upload-list .delete').remove();

        file.post.photo_id = res.id;

        // add photo_id into a hidden field of the form
        idsFiled = $('#uploadFiles');

        ids = idsFiled.val() + '|' + res.id;
        idsFiled.val(ids);
    }

    progress.toggleCancel(true, thisobj, function () {
        $.post_withck(thisobj.customSettings.jUrl + 'deletephoto', {
            page_id: thisobj.customSettings.subjectId,
            photo_id: file.post.photo_id

        }, function (s) {
            s = $.parseJSON(s);
            if(s.r) {
                progress.setError();
                progress.setStatus('删除时：' + errdetail[s.r]);
                allErrorFiles++;
        console.log('toggleCancel'+allErrorFiles);
            } else {
                progress.setCancelled();
                //progress.setStatus('已删除');

                // remove photo_id from the hidden field
                idsFiled = $('#uploadFiles');
                ids = idsFiled.val().replace('|'+file.post.photo_id, '');
                idsFiled.val(ids);

                setTimeout(function () {
                    progress.disappear();
                }, 2000);

                decrease_upload_count(thisobj);
            }
        })
    });
}

function uploadError (file, errorCode, message) {
    //console.log('> upload error');
    var thisobj = this,
        progress = new FileProgress(file, this.customSettings.progressTarget);

    progress.setError();
    progress.toggleCancel(true, thisobj);

    allErrorFiles++;
        console.log('uploadError'+allErrorFiles);
    progress.setStatus('失败');
    progress.removeDelIcon();
    $('.upload-list .delete').remove();

    switch (errorCode) {
        case SWFUpload.UPLOAD_ERROR.HTTP_ERROR:
            //progress.setStatus('*上传错误：' + message);
            progress.setStatus('失败');
            debug_message(this, 'HTTP Error', file, message);
            break;

        case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED:
            //progress.setStatus('*上传失败：' + message);
            progress.setStatus('失败');
            debug_message(this, 'Upload Failed', file, message);
            break;

        case SWFUpload.UPLOAD_ERROR.IO_ERROR:
            //progress.setStatus('*服务器IO错误', file, message);
            progress.setStatus('失败');
            debug_message(this, 'IO Error', file, message);
            break;

        case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR:
            //progress.setStatus('*安全错误');
            progress.setStatus('失败');
            debug_message(this, 'Security Error', file, message);
            break;

        case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
            //progress.setStatus('*上传达到上限');
            debug_message(this, 'Upload limit exceeded', file, message);
            progress.setStatus('失败');
            break;

        case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED:
            //progress.setStatus('*文件与要求不符');
            debug_message(this, 'File validation failed', file, message);
            progress.setStatus('失败');
            break;

        case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED:
            if (this.getStats().files_queued === 0) {
                document.getElementById(this.customSettings.cancelButtonId).disabled = true;
            }
            progress.setStatus('取消');
            progress.setCancelled();
            updateTotal(totalNum -= 1, totalSize -= file.size);

            // update error file number
            allErrorFiles--;
            if ($('.progressWrapper').length <= 20) {
                $('.continue-wrapper').removeClass('hidden');
            }
            break;

        case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
            progress.setStatus('停止');
            break;

        default:
            progress.setStatus('错误：' + errorCode);
            debug_message(this, errorCode, file, message);
            break;
    }
}

function uploadComplete (file, data) {
    if (this.getStats().files_queued === 0) {
        $('#' + this.customSettings.cancelButtonId)[0].disabled = true;
    }
}

function queueComplete (numFilesUploaded) {
    $('#upload-start').val('开始上传').removeAttr('disabled');
    $('.opt-btns').addClass('hidden');

    allFilesUploaded += (numFilesUploaded - allErrorFiles);

    if (allFilesUploaded > 0) {
      //  idsFiled.val(ids.split('|')[1]);

        // all photos uploaded successfully
        if (allFilesUploaded === numFilesUploaded) {
            $('#upload').submit();
            allErrorFiles = 0;
        } else {
            // show failed num
            $('#has-error').removeClass().find('b').text(allErrorFiles);

            // some photos uploaded failed
            $('.nextstep').removeClass('hidden');
        }
    } else {
        $('.continue-wrapper').removeClass('hidden');
        $('#has-error').removeClass().find('b').text(allErrorFiles);

        // some photos uploaded failed
        $('.nextstep').removeClass('hidden');
    }

    uploadStarted = false;
}
